package com.compus.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.json.JSONUtil;
import com.compus.constant.EnableStatus;
import com.compus.entity.po.Car;
import com.compus.entity.po.CarPosition;
import com.compus.entity.vo.CarPositionVo;
import com.compus.entity.vo.Result;
import com.compus.service.CarPositionService;
import com.compus.service.CarService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Tag(name = "校车")
@RestController
@RequestMapping("/car")
public class CarController {

    @Resource
    private CarService carService;

    @Resource
    private CarPositionService carPositionService;

    @Operation(summary = "获取校车位置列表")
    @GetMapping("/getCarPositionList")
    public Result<List<CarPositionVo>> list() {
        List<Car> list = carService.lambdaQuery()
                .eq(Car::getStatus, EnableStatus.ENABLE)
                .list();
        ArrayList<CarPositionVo> positionVos = new ArrayList<>();
        for (Car car : list) {
            CarPosition position = carPositionService.lambdaQuery()
                    .eq(CarPosition::getCarId, car.getId())
                    .orderByDesc(CarPosition::getCreateTime)
                    .last("limit 1")
                    .one();
            if (position==null){
                continue;
            }
            CarPositionVo vo = new CarPositionVo();
            vo.setCarId(car.getId());
            vo.setCarPositionId(position.getId().toString());
            vo.setPosition(position.getPosition());
            positionVos.add(vo);
        }
        return Result.success(positionVos);
    }

    /**
     *
     * @param map
     * @return
     */
    @SaIgnore
    @Operation(summary = "获取校车配置二维码")
    @PostMapping("/getCarConfigQrCode")
    public Result<String> getCarConfigQrCode(@RequestBody Map<String,Object> map) {
        QrConfig qrConfig = new QrConfig();
        qrConfig.setHeight(300);
        qrConfig.setWidth(300);
        String string = QrCodeUtil.generateAsBase64(JSONUtil.toJsonStr(map), qrConfig, "png");
        return Result.success(string);
    }

    @SaIgnore
    @Operation(summary = "获取校园车列表")
    @GetMapping("/getCarList")
    public Result<List<Car>> getCarList() {
        List<Car> list = carService.lambdaQuery()
                .list();
        return Result.success(list);
    }

}
